#!/bin/bash

# create_shared_directories.sh
# 功能说明:
# 1. 为一组用户创建共享目录。
# 2. 设置共享目录的权限，允许指定组内用户访问。
# 3. 支持从文件中读取用户列表，或通过命令行参数传入用户。

# 默认共享目录的父路径
DEFAULT_SHARED_DIR="/shared"

# 检查并创建共享目录
create_shared_directory() {
  local username="$1"
  local shared_dir="$DEFAULT_SHARED_DIR/$username"

  # 检查用户是否存在
  if ! id "$username" &>/dev/null; then
    echo "User $username does not exist. Skipping..."
    return
  fi

  # 创建共享目录
  if [[ ! -d "$shared_dir" ]]; then
    sudo mkdir -p "$shared_dir"
    echo "Created shared directory: $shared_dir"
  else
    echo "Shared directory $shared_dir already exists."
  fi

  # 设置目录权限
  sudo chown "$username":"$username" "$shared_dir"
  sudo chmod 770 "$shared_dir"
  echo "Permissions set for $shared_dir (owner: $username, group: $username, mode: 770)."
}

# 从文件批量创建共享目录
process_user_file() {
  local file="$1"

  if [[ ! -f "$file" ]]; then
    echo "File $file does not exist. Please provide a valid file."
    exit 1
  fi

  while IFS= read -r username; do
    [[ -z "$username" || "$username" == \#* ]] && continue
    create_shared_directory "$username"
  done <"$file"
}

# 主函数
main() {
  if [[ $# -lt 1 ]]; then
    echo "Usage: $0 [-f user_file] [username1 username2 ...]"
    echo "  -f user_file: Specify a file containing a list of usernames."
    echo "  username: Specify one or more usernames directly."
    exit 1
  fi

  if [[ "$1" == "-f" ]]; then
    shift
    if [[ -n "$1" ]]; then
      process_user_file "$1"
    else
      echo "Error: Missing file name after -f."
      exit 1
    fi
  else
    for username in "$@"; do
      create_shared_directory "$username"
    done
  fi
}

# 执行主函数
main "$@"

